from fastapi import FastAPI
from app.core.schedule import task_manager, start_scheduler
from app.api import alert_routes, history_routes, trigger_routes, task_group_routes
import logging

app = FastAPI(
    title="通用预警系统API",
    description="基于任务组的预警系统",
    version="1.0.0"
)

# 包含路由
app.include_router(alert_routes.router, prefix="/alert", tags=["预警规则管理"])
app.include_router(history_routes.router, prefix="/alert", tags=["预警历史查询"])
app.include_router(trigger_routes.router, prefix="/alert", tags=["手动触发"])
app.include_router(task_group_routes.router, prefix="/tasks", tags=["任务组管理"])

# 设置日志
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',  # 日志格式
    handlers=[
        logging.FileHandler("app.log"),  # 输出到文件
        #logging.StreamHandler()  # 同时输出到控制台（可选）
    ])
logger = logging.getLogger(__name__)


@app.on_event("startup")
async def startup_event():
    logger.info("应用启动中...")
    # 1. 初始化数据库表结构
    from app.db.models import Base
    from app.db.session import engine
    Base.metadata.create_all(bind=engine)
    logger.info("数据库初始化完成")

    # 2. 初始化预定义任务组
    from app.db.session import get_db
    db = next(get_db())
    try:
        from app.db.init_task_groups import init_predefined_task_groups
        init_predefined_task_groups(db)
        logger.info("预定义任务组初始化完成")
    except Exception as e:
        logger.error(f"初始化预定义任务组失败: {e}")
    finally:
        db.close()

    # 3. 启动任务调度器
    start_scheduler()
    logger.info("任务调度器已启动")


@app.on_event("shutdown")
async def shutdown_event():
    logger.info("应用关闭中...")
    from app.core.schedule import shutdown_scheduler
    shutdown_scheduler()
    logger.info("任务管理器已关闭")


@app.get("/")
async def root():
    return {"message": "基于任务组的预警系统API服务运行中"}